package com.woke.fragment;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatDialogFragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import android.widget.ViewSwitcher;

import com.bean.HuiKaBankBranchCode;
import com.bean.HuiKaBankBranchCodeData;
import com.bean.HuiKaBankCode;
import com.bean.HuiKaBankCodeData;
import com.http.HttpMethods;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.miguelcatalan.materialsearchview.MaterialSearchView;
import com.woke.adapter.HuiKaBankBranchViewProvider;
import com.woke.adapter.HuiKaBankViewProvider;
import com.woke.adapter.OnItemClickListener;
import com.woke.method.NetworkUtils;
import com.zhongcai.online.R;

import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * Created by Administrator on 2017/5/10 0010.
 * 汇卡 开户行选择
 */

public class HuiKaBankBranchDialogFragment extends AppCompatDialogFragment implements DialogInterface.OnKeyListener {

    private OnItemClickListener mItemClickListener;
    private MultiTypeAdapter mBankMulitypeAdapter, mBankBranchMulitypeAdapter;
    private Items mBankItems = new Items();
    private Items mBankBranchItems = new Items();
    private XRecyclerView mBankRecyclerView;
    private XRecyclerView mBankBranchRecyclerView;
    private ViewSwitcher mViewSwitcher;
    private int pageIndex = 0;
    private MaterialSearchView mBankSearchView;
    private MaterialSearchView mBranchSearchView;
    private Toolbar mBankToolbar;
    private Toolbar mBranchToolbar;
    private String mQueryBankStr, mQueryBranchStr;//总行和支行模糊查询字段
    private int mBandId;//总行编码id

    public void setOnItemClickListener(OnItemClickListener listener) {
        mItemClickListener = listener;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.AppTheme);
    }

    @Override
    public void setupDialog(Dialog dialog, int style) {
        super.setupDialog(dialog, style);

        Context context = dialog.getContext();
        View rootView = LayoutInflater.from(context).inflate(R.layout.fragment_dialog_bankcode, null);
        mBankRecyclerView = (XRecyclerView) rootView.findViewById(R.id.bankcode_recyclerView);
        mBankBranchRecyclerView = (XRecyclerView) rootView.findViewById(R.id.bank_branch_recyclerView);
        mViewSwitcher = (ViewSwitcher) rootView.findViewById(R.id.viewSwitcher);

        initBankToolbar(rootView);

        initBranchToolbar(rootView);

        initBank();
        initBankBranch();
        dialog.setContentView(rootView);
        getBankList(1, "");

        dialog.setOnKeyListener(this);
    }

    private void initBranchToolbar(View rootView) {
        mBranchSearchView = (MaterialSearchView) rootView.findViewById(R.id.searchView_bankBranchCode);
        mBranchSearchView.setCursorDrawable(R.drawable.color_cursor_white);
        mBranchToolbar = (Toolbar) rootView.findViewById(R.id.toolbar_bankBranchCode);
        mBranchToolbar.setTitle(R.string.choose_branch_bank_pufa);
        mBranchToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mViewSwitcher.showPrevious();
            }
        });

        mBranchToolbar.inflateMenu(R.menu.menu_search);
        Menu menu = mBranchToolbar.getMenu();
        MenuItem item = menu.findItem(R.id.action_search);
        mBranchSearchView.setMenuItem(item);
        mBranchSearchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                getBranchList(mBandId, 1, query);
                mQueryBranchStr = query;
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {

                return false;
            }
        });
    }

    private void initBankToolbar(View rootView) {
        mBankSearchView = (MaterialSearchView) rootView.findViewById(R.id.searchView_bankCode);
        mBankSearchView.setCursorDrawable(R.drawable.color_cursor_white);
        mBankToolbar = (Toolbar) rootView.findViewById(R.id.toolbar_bankcode);
        mBankToolbar.setTitle(R.string.choose_bank_pufa);
        mBankToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        mBankToolbar.inflateMenu(R.menu.menu_search);
        Menu menu = mBankToolbar.getMenu();
        MenuItem item = menu.findItem(R.id.action_search);
        mBankSearchView.setMenuItem(item);
        mBankSearchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                getBankList(1, query);
                mQueryBankStr = query;
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {

                return false;
            }
        });
    }

    private HuiKaBankCodeData mBankCodeData;

    private void getBankList(int page, String search) {
        if (NetworkUtils.isConnected(getContext())) {
            HttpMethods.getInstance().getHuiKaBankList(mBankListObserver, page, search);
        } else {
            showToast(getResources().getString(R.string.hint_error_server));
            dismiss();
        }
    }

    private HuiKaBankBranchCodeData mBankBranchData;

    private void getBranchList(int bankId, int page, String search) {
        if (NetworkUtils.isConnected(getContext())) {
            HttpMethods.getInstance().getHuiKaBranchBankList(mBranchListObserver, bankId, page, search);
        } else {
            showToast(getResources().getString(R.string.hint_error_server));
            dismiss();
        }
    }


    private void initBankBranch() {
        mBankBranchRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mBankBranchRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mBankBranchRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        mBankBranchRecyclerView.setLoadingMoreEnabled(true);

        mBankBranchMulitypeAdapter = new MultiTypeAdapter();
        mBankBranchMulitypeAdapter.register(HuiKaBankBranchCode.class, new HuiKaBankBranchViewProvider(listener));
        mBankBranchRecyclerView.setAdapter(mBankBranchMulitypeAdapter);

        mBankBranchMulitypeAdapter.setItems(mBankBranchItems);
        mBankBranchMulitypeAdapter.notifyDataSetChanged();

        mBankBranchRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                getBranchList(mBandId, 1, mQueryBranchStr);
                mBankBranchRecyclerView.refreshComplete();
            }

            @Override
            public void onLoadMore() {
                if (mBankBranchData != null) {
                    if (mBankBranchData.hasNext()) {
                        int page = mBankBranchData.getCurrent_page() + 1;
                        getBranchList(mBandId, page, mQueryBranchStr);
                    }
                }
                mBankBranchRecyclerView.loadMoreComplete();
            }
        });
    }

    private void initBank() {
        mBankRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mBankRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mBankRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        mBankRecyclerView.setLoadingMoreEnabled(true);
        mBankMulitypeAdapter = new MultiTypeAdapter();
        mBankMulitypeAdapter.register(HuiKaBankCode.class, new HuiKaBankViewProvider(listener));
        mBankRecyclerView.setAdapter(mBankMulitypeAdapter);

        mBankMulitypeAdapter.setItems(mBankItems);
        mBankMulitypeAdapter.notifyDataSetChanged();

        mBankRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                getBankList(1, mQueryBankStr);
                mBankRecyclerView.refreshComplete();
            }

            @Override
            public void onLoadMore() {
                if (mBankCodeData != null) {
                    if (mBankCodeData.hasNext()) {
                        int page = mBankBranchData.getCurrent_page() + 1;
                        getBankList(page, mQueryBankStr);
                    }
                }
                mBankRecyclerView.loadMoreComplete();
            }
        });
    }

    private Observer<HuiKaBankCodeData> mBankListObserver = new Observer<HuiKaBankCodeData>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(HuiKaBankCodeData value) {
            if (value != null) {
                mBankCodeData = value;
                List<HuiKaBankCode> list = value.getBanklist();
                if (list != null && list.size() > 0) {
                    if (value.getCurrent_page() == 0 || value.getCurrent_page() == 1) {
                        //如果是搜索框 点击搜索，page 和 next 不返回  或者返回第一页
                        mBankItems.clear();
                    }
                    pageIndex = 0;
                    mBankItems.addAll(list);
                    if (mBankMulitypeAdapter != null) {
                        ;
                        mBankMulitypeAdapter.notifyDataSetChanged();
                    }
                }

            }
        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {

        }
    };
    private Observer<HuiKaBankBranchCodeData> mBranchListObserver = new Observer<HuiKaBankBranchCodeData>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(HuiKaBankBranchCodeData value) {
            if (value != null) {
                mBankBranchData = value;
                List<HuiKaBankBranchCode> list = value.getBanklist();
                if (list != null && list.size() > 0) {

                    if (value.getCurrent_page() == 0 || value.getCurrent_page() == 1) {
                        //如果是搜索框 点击搜索，page 和 next 不返回  或者返回第一页
                        mBankBranchItems.clear();
                    }
                    pageIndex = 1;
                    mBankBranchItems.addAll(list);
                    if (mBankBranchMulitypeAdapter != null) {
                        mBankBranchMulitypeAdapter.notifyDataSetChanged();
                    }
                }

            }
        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {

        }
    };

    private Toast mToast;

    private void showToast(String msg) {
        if (getContext() == null) return;
        if (mToast == null) {
            mToast = Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT);
        }
        mToast.setText(msg);
        mToast.show();
    }

    private OnItemClickListener listener = new OnItemClickListener() {
        @Override
        public void OnItemClick(View view, int position) {
            if (mItemClickListener != null) {
                mItemClickListener.OnItemClick(view, position);
            }
        }

        @Override
        public void OnItemClick(View view, Object object, int position) {


            if (object instanceof HuiKaBankCode) {
                //总行
                HuiKaBankCode bankCode = (HuiKaBankCode) object;
                if (bankCode.getId()!=0) {
                    mBandId = bankCode.getId();
                    mViewSwitcher.showNext();
                    getBranchList(mBandId, 1, "");
                }

            } else if (object instanceof HuiKaBankBranchCode) {
                //支行
                dismiss();
            }
            if (mItemClickListener != null) {
                mItemClickListener.OnItemClick(view, object, position);
            }
        }
    };

    @Override
    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            if (pageIndex >= 1) {
                mViewSwitcher.showPrevious();
                pageIndex--;
                return true;
            } else {
                dismiss();
                return false;
            }
        }
        return false;
    }
}
